package cn.edu.ctbu.lastwork.demos.web.controller;

import cn.edu.ctbu.lastwork.demos.web.entity.Student;
import cn.edu.ctbu.lastwork.demos.web.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping
    public String listStudents(Model model) {
        model.addAttribute("students", studentRepository.findAll());
        return "students"; // 确保这里有一个相应的 students.html 模板文件
    }

    @GetMapping("/new")
    public String newStudentForm(Model model) {
        model.addAttribute("student", new Student());
        return "student-form"; // 确保 student-form.html 存在于 src/main/resources/templates 目录下
    }

    @PostMapping
    public String saveStudent(Student student) {
        studentRepository.save(student);
        return "redirect:/students";
    }
}
